package com.dongwu.common.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONObject;

import com.gexin.fastjson.JSON;

/**
 * HttpClient工具类
 * 
 * @author xyj
 *
 */
@SuppressWarnings("deprecation")
public class HttpClientUtils {

	private static StringBuilder entityStringBuilder = null;

	private static HttpResponse httpResponse = null;

	private static CloseableHttpClient httpClient = null;

	// ----------------------------------------------get请求区--------------------------------------------------------------
	/**
	 * get请求返回String
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String HttpGetResStr(String url) throws Exception {
		HttpGet httpget = HttpClientUtils.GetHttpClient(url);
		httpResponse = httpClient.execute(httpget);
		return HttpClientUtils.RespToString(httpResponse);
	}

	/**
	 * get请求返回Map<String,Object>
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> HttpGetResMap(String url) throws Exception {
		HttpGet httpget = HttpClientUtils.GetHttpClient(url);
		httpResponse = httpClient.execute(httpget);
		return HttpClientUtils.RespToMap(httpResponse);
	}

	// ----------------------------------------------Post请求区--------------------------------------------------------------
	/**
	 * post请求返回String
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String HttpPostResStr(String url) throws Exception {
		HttpPost httpget = HttpClientUtils.PostHttpClient(url);
		httpResponse = httpClient.execute(httpget);
		return HttpClientUtils.RespToString(httpResponse);
	}

	/**
	 * post请求返回Map<String,Object>
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> HttpPostResMap(String url) throws Exception {
		HttpPost httpget = HttpClientUtils.PostHttpClient(url);
		httpResponse = httpClient.execute(httpget);
		return HttpClientUtils.RespToMap(httpResponse);
	}
	
	/**
	 * jsonObj请求返回String
	 * 
	 * @param url
	 * @param jsonObj
	 * @return
	 * @throws Exception
	 */
	public static String PostJsonObjResStr(String url, JSONObject jsonObj) throws Exception {
		HttpPost httpPost = HttpClientUtils.PostHttpClient(url);
		httpPost.setEntity(new StringEntity(jsonObj.toString(), ContentType.create("application/json", "utf-8")));
		httpResponse = httpClient.execute(httpPost);
		return HttpClientUtils.RespToString(httpResponse);

	}

	/**
	 * jsonObj请求返回Map<String,Object>
	 * 
	 * @param url
	 * @param jsonObj
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> PostJsonObjResMap(String url, JSONObject jsonObj) throws Exception {
		HttpPost httpPost = HttpClientUtils.PostHttpClient(url);
		httpPost.setEntity(new StringEntity(jsonObj.toString(), ContentType.create("application/json", "utf-8")));
		httpResponse = httpClient.execute(httpPost);
		return HttpClientUtils.RespToMap(httpResponse);

	}

	/**
	 * jsonStr请求返回String
	 * 
	 * @param url
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	public static String PostJsonStrResStr(String url, String jsonStr) throws Exception {
		HttpPost httpPost = HttpClientUtils.PostHttpClient(url);
		httpPost.setEntity(new StringEntity(jsonStr, ContentType.create("application/json", "utf-8")));
		httpResponse = httpClient.execute(httpPost);
		return HttpClientUtils.RespToString(httpResponse);

	}

	/**
	 * jsonStr请求返回String
	 * 
	 * @param url
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> PostJsonStrResMap(String url, String jsonStr) throws Exception {
		HttpPost httpPost = HttpClientUtils.PostHttpClient(url);
		httpPost.setEntity(new StringEntity(jsonStr, ContentType.create("application/json", "utf-8")));
		httpResponse = httpClient.execute(httpPost);
		return HttpClientUtils.RespToMap(httpResponse);

	}

	/**
	 * 上传文件到远程服务器
	 * 
	 * @param serverUrl（服务器地址）
	 * @param File
	 *            （文件）
	 * @return
	 * @throws Exception
	 */
	public static String PostFileResMap(String serverUrl, File File) throws Exception {
		HttpPost httpPost = HttpClientUtils.PostHttpClient(serverUrl);
		MultipartEntity reqEntity = new MultipartEntity();
		FileBody fileBody = new FileBody(File);
		reqEntity.addPart("param", fileBody);// file1为请求后台的File upload;属性
		httpPost.setEntity(reqEntity);
		HttpResponse httpResponse = httpClient.execute(httpPost);
		/**
		 * 以下多文件上传
		 */
		// String[] filenames=fileNames.split(";");
		// MultipartEntity reqEntity = new MultipartEntity();
		// for(int i=0;i<filenames.length;i++) {
		// String fileName=filenames[i];
		//
		// FileBody fileBody = new FileBody(File);
		// reqEntity.addPart("param", fileBody);// file1为请求后台的File upload;属性
		//
		// }
		// httpPost.setEntity(reqEntity);
		// HttpResponse httpResponse = httpClient.execute(httpPost);
		// if (null != response && response.getStatusLine().getStatusCode() ==
		// 200) {
		// HttpEntity resEntity = response.getEntity();
		// if (null != resEntity) {
		// result = EntityUtils.toString(resEntity, HTTP.UTF_8);
		// System.out.println(result);
		// }
		// }
		return HttpClientUtils.RespToString(httpResponse);

	}

	// -------------------------------------------------------------------------------------------------------------------------------
	// ----------------------------------------------以下是httpclient配置--------------------------------------------------------------
	// -------------------------------------------------------------------------------------------------------------------------------
	/**
	 * 将HttpResponse中的json转为String输出
	 * 
	 * @param httpResponse
	 * @return
	 */
	public static String RespToString(HttpResponse httpResponse) throws Exception {
		try {
			// 处理返回的json
			HttpEntity entity = httpResponse.getEntity();
			entityStringBuilder = new StringBuilder();
			if (null != entity) {
				BufferedReader bufferedReader = new BufferedReader(
						new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024);
				String line = null;
				while ((line = bufferedReader.readLine()) != null) {
					entityStringBuilder.append(line);
				}
			}
			return entityStringBuilder.toString();

			// String result = null;
			// if (null != httpResponse &&
			// httpResponse.getStatusLine().getStatusCode() == 200) {
			// HttpEntity resEntity = httpResponse.getEntity();
			// if (null != resEntity) {
			// result = EntityUtils.toString(resEntity, HTTP.UTF_8);
			// System.out.println(result);
			// }
			// }
			// return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != httpClient) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	/**
	 * 将HttpResponse中的json转为Map<String,Object>输出
	 * 
	 * @param httpResponse
	 * @return
	 */
	public static Map<String, Object> RespToMap(HttpResponse httpResponse) throws Exception {
		return JSON.parseObject(HttpClientUtils.RespToString(httpResponse));
	}

	/**
	 * 初始化get请求并设置属性
	 * 
	 * @param url
	 * @return
	 */
	public static HttpGet GetHttpClient(String url) {
		httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(180 * 1000)
				.setConnectionRequestTimeout(180 * 1000).setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
		httpGet.setConfig(requestConfig);
		return httpGet;
	}

	/**
	 * 初始化post请求并设置属性
	 * 
	 * @param url
	 * @return
	 */
	public static HttpPost PostHttpClient(String url) {
		httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(180 * 1000)
				.setConnectionRequestTimeout(180 * 1000).setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
		httpPost.setConfig(requestConfig);
		return httpPost;
	}
}
